"""
在线词典 ： 客户端 发请求 得结果 展示
"""
import sys
from socket import *
class Handle:
    def __init__(self):
        self.server_address=("127.0.0.1",8888)
        self.sock=self._connect()
    def _connect(self):
        sock=socket()
        sock.connect(self.server_address)
        return sock
    def do_login(self,name,passwd):
        request=f"L\t{name}\t{passwd}"
        self.sock.send(request.encode())
        res=self.sock.recv(128)
        if res==b"T":
            print("登录成功")
            return True
        else:
            print("登录失败")


    def do_exit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")

    def do_sign(self,name,passwd):
        request=f"R\t{name}\t{passwd}"
        self.sock.send(request.encode())
        result=self.sock.recv(1024)
        if result==b"T":
            print("注册成功")
        else:
            print("注册失败")
    def do_query(self):
        while True:
            word=input("Word:")
            if not word or word=="##":
                break
            request=f"Q\t{word}"
            self.sock.send(request.encode())
            res=self.sock.recv(1024)
            if res==b"F":
                mean="Not Found!"
            else:
                mean=res.decode().split("\t",1)[1]
            print("%s : %s\n" %(word,mean))

    def do_hist(self):
        self.sock.send(b"H")
        data=self.sock.recv(1024*10)
        if data==b"F":
            print("您还没有查询记录")
        else:
            rows=data.decode().split("\t")[1].split(";")
            for row in rows:
                print(row)


class DictView:
    def __init__(self):
        self.handle=Handle()
    def _input_info(self):
        name = input("Name：")
        passwd = input("Password:")
        return name,passwd
    def __menu_1(self):
        while True:
            print("""
        ========== 登录界面 ==========
         1. 登录   2. 注册   3. 退出
        =============================
            """)
            cmd = input("请输入选项:")
            if cmd == "1":
               if self.handle.do_login(*self._input_info()):
                    self.menu_2()
            elif cmd == "2":
                self.handle.do_sign(*self._input_info())
            elif cmd == "3":
                self.handle.do_exit()
            else:
                print("请输入正确选项！")

    def menu_2(self):
        while True:
            print("""
        ============ 查询界面 ============
         1. 查单词   2. 历史记录   3. 注销
        =================================
            """)
            cmd = input("请输入选项:")
            if cmd == "1":
                self.handle.do_query()
            elif cmd == "2":
                self.handle.do_hist()
            elif cmd == "3":
                break
            else:
                print("请输入正确选项！")

    def main(self):
        self.__menu_1()

if __name__=='__main__':
    dict=DictView()
    dict.main()